import csv
import os
import datetime


class Account:
    def __init__(self, account_id, name, password, balance=0):
        self.account_id = account_id  # 账户ID
        self.name = name  # 账户名
        self.password = password  # 密码
        self.balance = balance  # 余额
        self.records = []  # 交易记录

    def save_money(self, amount):
        """存款操作"""
        if amount <= 0:
            return False, "存款金额必须大于0"

        self.balance += amount
        self.records.append({
            "type": "deposit",
            "amount": amount,
            "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "balance": self.balance
        })
        return True, f"存款成功，当前余额: {self.balance}"

    def take_money(self, amount):
        """取款操作"""
        if amount <= 0:
            return False, "取款金额必须大于0"
        if amount > self.balance:
            return False, "余额不足"

        self.balance -= amount
        self.records.append({
            "type": "withdraw",
            "amount": amount,
            "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "balance": self.balance
        })
        return True, f"取款成功，当前余额: {self.balance}"

    def send_money(self, target_account, amount):
        """转账操作"""
        if amount <= 0:
            return False, "转账金额必须大于0"
        if amount > self.balance:
            return False, "余额不足"

        self.balance -= amount
        target_account.balance += amount

        self.records.append({
            "type": "transfer_out",
            "amount": amount,
            "target": target_account.account_id,
            "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "balance": self.balance
        })

        target_account.records.append({
            "type": "transfer_in",
            "amount": amount,
            "source": self.account_id,
            "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "balance": target_account.balance
        })

        return True, f"转账成功，当前余额: {self.balance}"

    def get_records(self, count=10):
        """获取最近交易记录"""
        return self.records[-count:] if self.records else []


class Bank:
    def __init__(self, data_file="accounts.csv"):
        self.accounts = {}  # 账户字典
        self.data_file = data_file  # 数据文件
        self.load_data()  # 加载数据

    def load_data(self):
        """从CSV文件加载账户数据"""
        if not os.path.exists(self.data_file):
            return

        try:
            with open(self.data_file, 'r', newline='') as file:
                reader = csv.reader(file)
                # 跳过表头
                next(reader, None)

                for row in reader:
                    account_id, name, password, balance = row
                    account = Account(account_id, name, password, float(balance))
                    self.accounts[account_id] = account
        except Exception as e:
            print(f"加载数据出错: {e}")

    def save_data(self):
        """保存账户数据到CSV文件"""
        try:
            with open(self.data_file, 'w', newline='') as file:
                writer = csv.writer(file)
                writer.writerow(["account_id", "name", "password", "balance"])

                for account in self.accounts.values():
                    writer.writerow([
                        account.account_id,
                        account.name,
                        account.password,
                        account.balance
                    ])
        except Exception as e:
            print(f"保存数据出错: {e}")

    def new_account(self, name, password, initial_money=0):
        """创建新账户"""
        # 生成唯一账户ID（简化版）
        account_id = f"ACC{len(self.accounts) + 1:05d}"

        account = Account(account_id, name, password, initial_money)
        self.accounts[account_id] = account
        self.save_data()

        return account_id

    def find_account(self, account_id):
        """查找账户"""
        return self.accounts.get(account_id)

    def check_password(self, account_id, password):
        """验证账户密码"""
        account = self.find_account(account_id)
        if account and account.password == password:
            return account
        return None


class ConsoleUI:
    def __init__(self, bank):
        self.bank = bank  # 银行对象
        self.current_user = None  # 当前登录用户

    def clear_screen(self):
        """清屏"""
        os.system('cls' if os.name == 'nt' else 'clear')

    def show_menu(self):
        """显示主菜单"""
        self.clear_screen()
        print("\n===== 简易银行系统 =====")

        if self.current_user:
            print(f"当前用户: {self.current_user.name}")
            print("1. 查余额")
            print("2. 存钱")
            print("3. 取钱")
            print("4. 转账")
            print("5. 查记录")
            print("6. 退出登录")
        else:
            print("1. 登录")
            print("2. 注册")

        print("0. 退出系统")

    def start(self):
        """启动系统"""
        while True:
            self.show_menu()
            choice = input("\n请选择操作: ")

            if self.current_user:
                if choice == '1':
                    self.show_balance()
                elif choice == '2':
                    self.save_money()
                elif choice == '3':
                    self.take_money()
                elif choice == '4':
                    self.send_money()
                elif choice == '5':
                    self.show_records()
                elif choice == '6':
                    self.current_user = None
                elif choice == '0':
                    break
            else:
                if choice == '1':
                    self.login()
                elif choice == '2':
                    self.register()
                elif choice == '0':
                    break

            input("\n按Enter键继续...")

    def login(self):
        """用户登录"""
        account_id = input("请输入账户ID: ")
        password = input("请输入密码: ")

        account = self.bank.check_password(account_id, password)
        if account:
            self.current_user = account
            print("登录成功!")
        else:
            print("账户ID或密码错误!")

    def register(self):
        """用户注册"""
        name = input("请输入姓名: ")
        password = input("请输入密码: ")

        try:
            initial_money = float(input("请输入初始存款金额: "))
            if initial_money < 0:
                print("初始存款不能为负数!")
                return

            account_id = self.bank.new_account(name, password, initial_money)
            print(f"注册成功! 您的账户ID是: {account_id}")
        except ValueError:
            print("请输入有效的金额!")

    def show_balance(self):
        """显示余额"""
        print(f"当前余额: {self.current_user.balance}")

    def save_money(self):
        """存钱操作"""
        try:
            amount = float(input("请输入存款金额: "))
            success, message = self.current_user.save_money(amount)
            print(message)

            if success:
                self.bank.save_data()
        except ValueError:
            print("请输入有效的金额!")

    def take_money(self):
        """取钱操作"""
        try:
            amount = float(input("请输入取款金额: "))
            success, message = self.current_user.take_money(amount)
            print(message)

            if success:
                self.bank.save_data()
        except ValueError:
            print("请输入有效的金额!")

    def send_money(self):
        """转账操作"""
        target_id = input("请输入目标账户ID: ")
        target_account = self.bank.find_account(target_id)

        if not target_account:
            print("目标账户不存在!")
            return

        try:
            amount = float(input("请输入转账金额: "))
            success, message = self.current_user.send_money(target_account, amount)
            print(message)

            if success:
                self.bank.save_data()
        except ValueError:
            print("请输入有效的金额!")

    def show_records(self):
        """显示交易记录"""
        records = self.current_user.get_records()

        if not records:
            print("暂无交易记录")
            return

        print("\n最近交易记录:")
        print("{:<10} {:<15} {:<10} {:<15} {:<10}".format(
            "类型", "时间", "金额", "相关账户", "余额"
        ))

        for r in records:
            r_type = r["type"]
            if r_type == "deposit":
                r_type = "存款"
                related = ""
            elif r_type == "withdraw":
                r_type = "取款"
                related = ""
            elif r_type == "transfer_out":
                r_type = "转出"
                related = r["target"]
            elif r_type == "transfer_in":
                r_type = "转入"
                related = r["source"]

            print("{:<10} {:<15} {:<10} {:<15} {:<10}".format(
                r_type,
                r["time"],
                r["amount"],
                related,
                r["balance"]
            ))


# 主程序入口
def main():
    bank = Bank()
    ui = ConsoleUI(bank)
    ui.start()


if __name__ == "__main__":
    main()
